<!--
  - Copyright (c) 2018.
  - 北京九思金信科技有限公司对该文件内容保留所有权利。
  - 未经许可，不得私自拷贝、传播、发布、引用该文件内容，违者将被追究法律责任。
  -->

<template>
    <div style="text-align: left">
        <el-card>
            <el-header class="headerClass">
              <ft-return-btn text="返回列表" @click="goBack()"></ft-return-btn>
            </el-header>
            <div v-if="editShow">
                <el-button style="float: right;" size="small" @click="edit()" plain>编辑</el-button>
            </div>
            <el-form ref="formRef" size="small" :model="formData" label-width="100px"
                :inline="true" :disabled="formDisabled" style="padding-top: 20px;" :rules="rules">
                <div v-if="editShow">
                    <span class="templateClass">{{formData.templateName}}</span>
                </div>
                <div v-if="formDisabled">
                    <el-row>
                        <el-col :md="8" :lg="6" v-for="(item, index) in formData.gradeScope" :key="index">
                            <el-form-item :label='getLabel(item.rating_grade)'>
                                <span v-if="index===formData.gradeScope.length-1">{{item.max_score}}(以下)</span>
                                <span v-else>{{item.min_score}}(含)&nbsp;~{{item.max_score}}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="创建时间" prop="creationTs">
                                <span>{{formData.creationDate}}</span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <el-row v-if="!formData.ratingTemplateId" type="flex" class="tip">新建模版</el-row>
                <el-card v-if="!formDisabled" :class="{editClass: formData.ratingTemplateId, addClass: !formData.ratingTemplateId}">
                    <div>
                        <el-row type="flex">
                            <el-col :md="12" :lg="12">
                                <el-form-item label="模版名称" prop="templateId">
                                    <span v-if="formData.ratingTemplateId">{{formData.templateName}}</span>
                                    <ft-quota-category  v-else
                                                        v-model="formData.templateId"
                                                        :categoryProp="categoryLarge"
                                                        @change="categoryLargeChange"
                                                        style="width: 100%">
                                    </ft-quota-category>
                                </el-form-item>
                            </el-col>
                            <el-col :md="12" :lg="12">
                                <el-form-item label="创建时间" prop="creationTs">
                                    <span>{{formData.creationDate}}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col v-for="(item, index) in formData.gradeScope" :key="index" :md="24" :lg="12">
                                <el-form-item v-if="index!=formData.gradeScope.length-1" :label='getLabel(item.rating_grade)'>
                                    <el-input v-model="item.min_score" @keyup.native="proving(item, 'min_score')" style="width: 46%">
                                        <template slot="append">(含)</template>
                                    </el-input>
                                    <el-button type="text" class="btn-class" disabled>~</el-button>
                                    <el-input v-model="item.max_score" @keyup.native="proving(item, 'max_score')" style="width: 46%"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <div v-for="(item, index) in formData.gradeScope" :key="index">
                            <el-row v-if="index===formData.gradeScope.length-1">
                                <el-col :md="24" :lg="12">
                                    <el-form-item :label='getLabel(item.rating_grade)'>
                                        <el-input v-model="item.max_score" @keyup.native="proving(item, 'max_score')">
                                            <template slot="append">(以下)</template>
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                        <hr v-if="formData.ratingTemplateId" class="hrClass">
                        <el-row style="padding: 16px 36px 16px 0px">
                            <el-col align="right">
                                <el-button size="small" @click="clickCancel" :disabled="cancelDisabled">取消</el-button>
                                <el-button type="primary" size="small" @click="clickSave" :disabled="saveDisabled">保存</el-button>
                            </el-col>
                        </el-row>
                    </div>
                </el-card>
            </el-form>
        </el-card>
        <el-card v-if="formData.ratingTemplateId">
            <ft-tabs v-model="activeName" @tab-click="handleClick" :stretch="true">
                <ft-tab-pane
                    v-for="item in formData.quotaCategoryVOS"
                    :key="item.quotaCategorySubId"
                    :label="item.quotaCategorySubName"
                    :name="item.quotaCategorySubName">
                    <el-card class="el-card-tab">
                        <el-table :data="item.indicationDOS" style="width: 100%;">
                            <el-table-column label="参数名称" align="left">
                                <template slot-scope="scope">
                                    <div v-for="(dimension, index) in scope.row.scoreDimensionVOS" :key="dimension.scoreDimensionId" style="padding: 16px 0 10px">
                                        <el-checkbox v-model="dimension.checkAllFlag"
                                                     @change="handleCheckAllChange(dimension)"
                                                     :disabled="formDisabled">
                                                     {{dimension.scoreDimensionName}}（有以下待选项）
                                        </el-checkbox>
                                        <el-checkbox-group v-model="dimension.checkedScoreIds" @change="handleCheckedScoreChange($event, dimension)">
                                            <ul>
                                                <li v-for="score in dimension.scoreVOS" :key="score.scoreId">
                                                    <el-checkbox :label="score.scoreId"
                                                                 :disabled="scope.row.quotaProperty=='QUANTITATIVE' ? true : formDisabled"
                                                                 class="checkbox-class">
                                                                 {{score.scoreResult}}
                                                    </el-checkbox>
                                                </li>
                                            </ul>
                                        </el-checkbox-group>
                                        <hr v-if="scope.row.scoreDimensionVOS.length > 1 && index < scope.row.scoreDimensionVOS.length-1" class="hr-class">
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                </ft-tab-pane>
            </ft-tabs>
        </el-card>
    </div>
</template>

<script>
import FtDatePicker from "../../ft/FtDatePicker.vue";
import FtQuotaCategory from "../../ft/FtQuotaCategory.vue";
export default {
    components: {FtDatePicker, FtQuotaCategory},
    props: {
        propsData: {
            type: Object,
            default: null
        },
        isFormDisabled: {
            type: Boolean,
            default: true
        },
        propActiveName: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            //默认显示tab页签
            activeName: '',
            //编辑显示控制
            editShow: false,
            //按钮显示控制
            editFlag: false,
            //不可编辑
            formDisabled: true,
            //保存按钮控制
            saveDisabled: true,
            //取消按钮控制
            cancelDisabled: true,
            //表单数据（用于取消数据回退）
            rollBackFormData: {},
            //表单数据
            formData: {
                gradeScope:[]
            },
            //指标分类标识：指标大类
            categoryLarge: 'LARGE',
            //评级等级默认划分
            gradeScope: [
                {
                    rating_grade: 'AAA',
                    max_score: 100,
                    min_score: 90
                },
                {
                    rating_grade: 'AA',
                    max_score: 89,
                    min_score: 85
                },
                {
                    rating_grade: 'A',
                    max_score: 84,
                    min_score: 80
                },
                {
                    rating_grade: 'BBB',
                    max_score: 79,
                    min_score: 70
                },
                {
                    rating_grade: 'BB',
                    max_score: 69,
                    min_score: 65
                },
                {
                    rating_grade: 'B',
                    max_score: 64,
                    min_score: 60
                },
                {
                    rating_grade: 'C',
                    max_score: 60
                }
            ],
            //校验规则
            rules: {
                templateId: [
                    {
                        required: true, //是否必填
                        message: '模版名称不能为空', //规则
                        trigger: 'blur'  //何事件触发
                    },
                ],
            },
        }
    },
    mounted(){
        this.formData=JSON.parse(JSON.stringify(this.propsData))
        this.activeName=JSON.parse(JSON.stringify(this.propActiveName))
        this.rollBackFormData=JSON.parse(JSON.stringify(this.propsData))
        this.editShow=this.isFormDisabled
        this.formDisabled=this.isFormDisabled
        this.editFlag=!this.isFormDisabled
        this.saveDisabled=this.isFormDisabled
        this.cancelDisabled=this.isFormDisabled
    },
    methods: {
        //计分项选择
        handleCheckedScoreChange(val, dimension){
            dimension.checkAllFlag = val.length > 0 ? true : false
            var scores = dimension.scoreVOS
            if(val.length > 0){
                if(this.formData.templateElement==null){
                    this.formData.templateElement=[]
                }
                dimension.checkAllFlag = true
                for(var i in val){
                    if(!this.formData.templateElement.includes(val[i])){
                        this.formData.templateElement.push(val[i])
                    }
                }
                //去除勾选移除的计分项
                for(var i in scores){
                    for(var j in this.formData.templateElement){
                        if(this.formData.templateElement[j] == scores[i].scoreId
                            && !val.includes(scores[i].scoreId)){
                            this.formData.templateElement.splice(j, 1)
                        }
                    }
                }
            }else{
                for(var i in scores){
                    for(var j in this.formData.templateElement){
                        if(this.formData.templateElement[j] == scores[i].scoreId){
                            this.formData.templateElement.splice(j, 1)
                        }
                    }
                }
            }
        },
        //计分维度全选事件
        handleCheckAllChange(dimension){
            var scores = dimension.scoreVOS
            dimension.checkedScoreIds = dimension.checkAllFlag ? scores.map(scores=>scores.scoreId) : []
            for(var i in scores){
                if(this.formData.templateElement==null){
                    this.formData.templateElement=[]
                }
                if(dimension.checkAllFlag){
                    this.formData.templateElement.push(scores[i].scoreId)
                }else{
                    for(var j in this.formData.templateElement){
                        if(this.formData.templateElement[j] == scores[i].scoreId){
                            this.formData.templateElement.splice(j, 1)
                        }
                    }
                }
            }
        },
        //tab chang事件
        handleClick(tab, event){
            this.activeName = tab.name
        },
        //返回列表
        goBack(){
            this.$emit("returnList")
        },
        //编辑
        edit() {
            this.editShow=false
            this.editFlag=true
            this.formDisabled=false
            this.saveDisabled=false
            this.cancelDisabled=false
            this.rollBackFormData=JSON.parse(JSON.stringify(this.formData))
        },
        //模版信息保存
        clickSave(){
            this.$refs.formRef.validate((valid) => {
                if (valid && this.validDivide()) {
                    let url = "/joys-rest/lss-customer/template/save"
                    this.$http.put(url, this.formData).then(
                        resp => {
                            this.formData = resp.body
                            this.formDisabled=true
                            this.saveDisabled=true
                            this.cancelDisabled=true
                            this.editFlag=false
                            this.editShow=true
                            this.$message.success("保存成功！")
                            this.rollBackFormData=JSON.parse(JSON.stringify(resp.body))
                        },
                        resp => {
                            this.$message.error(resp.body.message)
                        }
                    )
                }
            })
        },
        //评级划分保存校验
        validDivide(){
            var gradeScope = this.formData.gradeScope
            for(var i in gradeScope){
                var scope = gradeScope[i]
                //校验同一等级内临界值范围
                if(scope.max_score<scope.min_score){
                    this.$message.error(this.getLabel(scope.rating_grade)+"：最小值不能大于最大值！")
                    return false
                }else{
                    //校验相邻等级临界值范围
                    if(i > 0){
                        var scope_last = gradeScope[i-1]
                        //等级C小于处理
                        if(i == gradeScope.length - 1){
                            if(scope_last.min_score < scope.max_score){
                                this.$message.error(this.getLabel(scope.rating_grade)+"应在"+scope_last.min_score+"以下")
                                return false
                            }
                        }else{
                            if(scope_last.min_score <= scope.max_score){
                                this.$message.error(this.getLabel(scope_last.rating_grade)+"最小值应大于"+this.getLabel(scope.rating_grade)+"最大值")
                                return false
                            }
                        }
                    }
                }
            }
            return true
        },
        //取消
        clickCancel(){
            if(this.formData.ratingTemplateId){
                this.formData=JSON.parse(JSON.stringify(this.rollBackFormData))
                this.editFlag=false
                this.editShow=true
                this.formDisabled=true
                this.saveDisabled=true
                this.cancelDisabled=true
            }else{
                this.$emit("returnList")
            }
        },
        //动态构造label
        getLabel(val){
            return '等级(' + val + ')'
        },
        //模版change事件
        categoryLargeChange(params){
            this.formData.templateId = params.itemId
            //初始化评级等级
            if(this.formData.templateId){
                this.$set(this.formData, 'gradeScope', JSON.parse(JSON.stringify(this.gradeScope)))
                this.showScore = true
            }
        },
        //分值校验只能输入正整数 /[^\.\d]/g
        proving(obj, flag){
            if(flag=='max_score'){
                obj.max_score = obj.max_score.replace(/[^\.\d]/g,'').replace(/\b(0+)/gi,"").replace(/[^0-9.]/g,'').replace('.','')
                if(obj.max_score <= 0){
                    obj.max_score = 0
                }
                if(obj.max_score>100){
                    obj.max_score = 100
                }
            }else{
                obj.min_score = obj.min_score.replace(/[^\.\d]/g,'').replace(/\b(0+)/gi,"").replace(/[^0-9.]/g,'').replace('.','')
                if(obj.min_score <= 0){
                    obj.min_score = 0
                }
                if(obj.min_score>100){
                    obj.min_score = 100
                }
            }
        },
    }
}
</script>
<style scoped>
.templateClass {
    font-family: "PingFangSC-Medium";
    font-size: 28px;
    color: #2A2D2E;
    line-height: 36px;
    padding-left: 24px;
}
.el-card-tab >>> .el-card__body {
    padding: 0 12px;
    min-height: 400px;
}
.spanclass {
    font-family:"Microsoft" !important;
    font-size: 20px !important;
    font-weight: bold;
}
.editClass >>> .el-card__body {
    background-color: #F4F8F9;
    width: 100%;
}
.addClass >>> .el-card__body {
    background-color: #F4F8F9;
    padding: 48px 76px 16px 76px;
    width: 100%;
}
.headerClass {
    text-align: left;
    font-size: 12px;
    height: 60px;
    background-color: #f0f8ff00 !important;
    padding: 20px
}
li {
    list-style-type:none;
    line-height: 14px;
    padding: 6px 0;
}
.hrClass {
    margin-top: 24px;
    border-width: thin;
    border: 0.5px solid rgba(179,179,179,0.20);
}
.hr-class {
    margin-bottom: 0;
    border-width: thin;
    border: 0.5px solid rgba(179,179,179,0.20);
}
.btn-class {
    font-family: "PingFangSC-Regular";
    font-size: 14px;
    color: #8C8C8C;
    letter-spacing: 0;
    text-align: right;
    line-height: 16px;
    text-align: center;
    width: 6.5%;
}
.checkbox-class {
    padding-right: 10px;
}
.checkbox-class >>> .el-checkbox__label {
    white-space: normal;
    word-break: break-all;
    vertical-align: middle;
}
</style>
